import { Controller } from 'egg';
const path = require('path');
const mkdirp = require('mkdirp');

export default class CommonController extends Controller {

  /**
   * @api {get} common/getCaptcha 获取验证码
   *  
   * @apiName getCaptcha
   * @apiGroup Common
   * @apiDescription 获取验证码
   */
  public async getCaptcha() {
    const { ctx } = this;
    let captcha = await this.service.tools.captcha(); // 服务里面的方法
    ctx.response.type = 'svg';  // 知道你个返回的类型
    ctx.session.userInfo = { loginCode: captcha.text };
    ctx.body = captcha.data; // 返回一张图片
  }

  /**
   * @api {post} common/sendEmail 邮件发送
   *  
   * @apiName sendEmail
   * @apiGroup Common
   * @apiDescription 邮件发送
   * @apiParam {String} [revicer] 接收人邮箱
   * @apiParam {String} [title] 文章标题
   * @apiParam {String} text 渲染成TEXT文本的内容
   * @apiParam {String} content 渲染成HTML文本的内容
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   */
  public async sendEmail(ctx) {
    let obj: { revicer, title, text, content } = ctx.request.body;
    await this.ctx.service.tools.email({
      revicer: obj.revicer,
      title: obj.title,
      text: obj.text,
      content: obj.content
    });
    this.ctx.response.body = {
      code: 200,
      status: '成功'
    };
  }

  /**
   * @api {post} common/upFile 图片上传(公共)
   *  
   * @apiName upFile
   * @apiGroup Common
   * @apiDescription 图片上传
   * @apiParam {String} type 业务类型
   * @apiParam {String} image 图片
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   */
  public async upFile() {
    let ctx = this.ctx;
    try {
      const file = ctx.request.files[0];
      const bo = ctx.request.body;
      let imagePath = path.join(__dirname,
        bo.type ? `../public/images/${bo.type}` : '../public/images');
      let isExist = await this.ctx.helper.getStat(imagePath);
      if (!isExist) {
        mkdirp.sync(imagePath, {});
      }
      let timeStamp: any = new Date().getTime();
      let templateFileArray = file.filename.split('.').reverse();
      templateFileArray.splice(1, 0, timeStamp);
      let newCreateFile = templateFileArray.reverse().join('.');
      let destPath = path.join(imagePath, newCreateFile)
      let status = await this.ctx.service.files.upFile(file, destPath);
      if (status) {
        const realPath = ctx.helper.replaceAll(path.join(`static/images/${bo.type}`, newCreateFile), '\\\\', '/');
        this.ctx.response.body = {
          code: 200,
          data: [realPath],
          status: '成功'
        };
      }

    } catch (err) {
      console.log(err);
    }

  }

  /**
   * @api {post} common/delFile 文件删除(公共)
   *  
   * @apiName delFile
   * @apiGroup Common
   * @apiDescription 文件删除
   * @apiParam {String} type 业务类型
   * @apiParam {String} fileName 文件名
   * @apiHeaderExample {json} headers:
   *     {
   *       "token": "admin_token"
   *     }
   */
  public async delFile(ctx) {
    let { type, fileName } = ctx.request.body;
    try {
      let absolutePath = path.join(__dirname, '../public/images', `${type}/${fileName}`);
      if (!type || !fileName) {
        throw ctx.helper.getErrorMsg(207);
      }
      const pathExist = await ctx.helper.getStat(absolutePath);
      if (pathExist) {
        const status = await ctx.service.files.delFile(absolutePath);
        if (status) {
          ctx.response.body = {
            code: 200,
            status: '删除成功'
          };
        } else {
          throw ctx.helper.getErrorMsg(220);
        }
      } else {
        throw ctx.helper.getErrorMsg(221);
      }

    } catch (err_info) {
      ctx.response.body = err_info;
    }
  }
}
